import { Request, Response } from 'express';
import { Op } from 'sequelize';
import Product from '../models/Product';
import ProductSku from '../models/ProductSku';
import Category from '../models/Category';
import Brand from '../models/Brand';
import { successResponse, errorResponse } from '../utils/response';
import { asyncHandler } from '../utils/asyncHandler';

class ProductController {
  /**
   * 创建商品
   */
  createProduct = asyncHandler(async (req: Request, res: Response) => {
    const {
      name,
      subtitle,
      categoryId,
      brandId,
      spuCode,
      mainImage,
      images,
      videoUrl,
      price,
      marketPrice,
      costPrice,
      stockQuantity = 0,
      unit = '件',
      weight,
      volumeLength,
      volumeWidth,
      volumeHeight,
      keywords,
      description,
      specifications,
      serviceInfo,
      shippingInfo,
      status = 1,
      isRecommend = 0,
      isNew = 0,
      isHot = 0,
      sortOrder = 0,
      skus = []
    } = req.body;

    // 验证分类是否存在
    const category = await Category.findByPk(categoryId);
    if (!category) {
      return errorResponse(res, '商品分类不存在', 400);
    }

    // 验证品牌是否存在（如果提供了品牌ID）
    if (brandId) {
      const brand = await Brand.findByPk(brandId);
      if (!brand) {
        return errorResponse(res, '商品品牌不存在', 400);
      }
    }

    // 检查SPU编码是否重复
    if (spuCode) {
      const existingProduct = await Product.findOne({
        where: { spuCode }
      });
      if (existingProduct) {
        return errorResponse(res, 'SPU编码已存在', 400);
      }
    }

    // 创建商品
    const product = await Product.create({
      name,
      subtitle,
      categoryId,
      brandId,
      spuCode,
      mainImage,
      images,
      videoUrl,
      price,
      marketPrice,
      costPrice,
      stockQuantity,
      unit,
      weight,
      volumeLength,
      volumeWidth,
      volumeHeight,
      keywords,
      description,
      specifications,
      serviceInfo,
      shippingInfo,
      status,
      isRecommend,
      isNew,
      isHot,
      sortOrder
    });

    // 创建SKU（如果提供了SKU数据）
    if (skus && skus.length > 0) {
      const skuData = skus.map((sku: any) => ({
        ...sku,
        productId: product.id
      }));
      await ProductSku.bulkCreate(skuData);
    }

    // 获取完整的商品信息（包含关联数据）
    const createdProduct = await Product.findByPk(product.id, {
      include: [
        { model: Category, as: 'category' },
        { model: Brand, as: 'brand' },
        { model: ProductSku, as: 'skus' }
      ]
    });

    return successResponse(res, createdProduct, '创建商品成功', 200);
  });

  /**
   * 获取商品列表（分页）
   */
  getProductList = asyncHandler(async (req: Request, res: Response) => {
    const queryParams = (req.query as any).params || req.query;
    const {
      page = 1,
      pageSize = 10,
      keyword = '',
      categoryId = '',
      brandId = '',
      status = '',
      isRecommend = '',
      isNew = '',
      isHot = '',
      minPrice = '',
      maxPrice = ''
    } = queryParams;

    const offset = (Number(page) - 1) * Number(pageSize);
    const limit = Number(pageSize);

    // 构建查询条件
    const whereCondition: any = {};

    if (keyword) {
      whereCondition[Op.or] = [
        { name: { [Op.like]: `%${keyword}%` } },
        { subtitle: { [Op.like]: `%${keyword}%` } },
        { keywords: { [Op.like]: `%${keyword}%` } }
      ];
    }

    if (categoryId) {
      whereCondition.categoryId = Number(categoryId);
    }

    if (brandId) {
      whereCondition.brandId = Number(brandId);
    }

    if (status !== '') {
      whereCondition.status = Number(status);
    }

    if (isRecommend !== '') {
      whereCondition.isRecommend = Number(isRecommend);
    }

    if (isNew !== '') {
      whereCondition.isNew = Number(isNew);
    }

    if (isHot !== '') {
      whereCondition.isHot = Number(isHot);
    }

    if (minPrice || maxPrice) {
      whereCondition.price = {};
      if (minPrice) {
        whereCondition.price[Op.gte] = Number(minPrice);
      }
      if (maxPrice) {
        whereCondition.price[Op.lte] = Number(maxPrice);
      }
    }

    const { count, rows } = await Product.findAndCountAll({
      where: whereCondition,
      include: [
        { model: Category, as: 'category' },
        { model: Brand, as: 'brand' },
        { model: ProductSku, as: 'skus' }
      ],
      offset,
      limit,
      order: [['sortOrder', 'DESC'], ['createdAt', 'DESC']],
      distinct: true
    });

    const result = {
      list: rows,
      total: count,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: Math.ceil(count / Number(pageSize))
    };

    return successResponse(res, result, '获取商品列表成功');
  });

  /**
   * 获取商品详情
   */
  getProductDetail = asyncHandler(async (req: Request, res: Response) => {
    const { id } = req.params;

    const product = await Product.findByPk(id, {
      include: [
        { model: Category, as: 'category' },
        { model: Brand, as: 'brand' },
        { model: ProductSku, as: 'skus' }
      ]
    });

    if (!product) {
      return errorResponse(res, '商品不存在', 404);
    }

    return successResponse(res, product, '获取商品详情成功');
  });

  /**
   * 更新商品
   */
  updateProduct = asyncHandler(async (req: Request, res: Response) => {
    const { id } = req.params;
    const updateData = req.body;

    const product = await Product.findByPk(id);
    if (!product) {
      return errorResponse(res, '商品不存在', 404);
    }

    // 验证分类是否存在
    if (updateData.categoryId) {
      const category = await Category.findByPk(updateData.categoryId);
      if (!category) {
        return errorResponse(res, '商品分类不存在', 400);
      }
    }

    // 验证品牌是否存在
    if (updateData.brandId) {
      const brand = await Brand.findByPk(updateData.brandId);
      if (!brand) {
        return errorResponse(res, '商品品牌不存在', 400);
      }
    }

    // 检查SPU编码是否重复
    if (updateData.spuCode && updateData.spuCode !== product.spuCode) {
      const existingProduct = await Product.findOne({
        where: { 
          spuCode: updateData.spuCode,
          id: { [Op.ne]: id }
        }
      });
      if (existingProduct) {
        return errorResponse(res, 'SPU编码已存在', 400);
      }
    }

    await product.update(updateData);

    // 获取更新后的完整商品信息
    const updatedProduct = await Product.findByPk(id, {
      include: [
        { model: Category, as: 'category' },
        { model: Brand, as: 'brand' },
        { model: ProductSku, as: 'skus' }
      ]
    });

    return successResponse(res, updatedProduct, '更新商品成功');
  });

  /**
   * 删除商品
   */
  deleteProduct = asyncHandler(async (req: Request, res: Response) => {
    const { id } = req.params;

    const product = await Product.findByPk(id);
    if (!product) {
      return errorResponse(res, '商品不存在', 404);
    }

    // 删除关联的SKU
    await ProductSku.destroy({
      where: { productId: id }
    });

    // 删除商品
    await product.destroy();

    return successResponse(res, null, '删除商品成功');
  });

  /**
   * 批量删除商品
   */
  batchDeleteProducts = asyncHandler(async (req: Request, res: Response) => {
    const { ids } = req.body;

    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return errorResponse(res, '请提供要删除的商品ID列表', 400);
    }

    // 删除关联的SKU
    await ProductSku.destroy({
      where: { productId: { [Op.in]: ids } }
    });

    // 删除商品
    const deletedCount = await Product.destroy({
      where: { id: { [Op.in]: ids } }
    });

    return successResponse(res, { deletedCount }, `成功删除${deletedCount}个商品`);
  });

  /**
   * 更新商品状态
   */
  updateProductStatus = asyncHandler(async (req: Request, res: Response) => {
    const { id } = req.params;
    const { status } = req.body;

    const product = await Product.findByPk(id);
    if (!product) {
      return errorResponse(res, '商品不存在', 404);
    }

    await product.update({ status });

    const updatedProduct = await Product.findByPk(id, {
      include: [
        { model: Category, as: 'category' },
        { model: Brand, as: 'brand' }
      ]
    });

    return successResponse(res, updatedProduct, '更新商品状态成功');
  });

  /**
   * 获取商品统计信息
   */
  getProductStats = asyncHandler(async (req: Request, res: Response) => {
    const totalProducts = await Product.count();
    const onShelfProducts = await Product.count({ where: { status: 1 } });
    const offShelfProducts = await Product.count({ where: { status: 0 } });
    const preOrderProducts = await Product.count({ where: { status: 2 } });
    const recommendProducts = await Product.count({ where: { isRecommend: 1 } });
    const newProducts = await Product.count({ where: { isNew: 1 } });
    const hotProducts = await Product.count({ where: { isHot: 1 } });

    const stats = {
      totalProducts,
      onShelfProducts,
      offShelfProducts,
      preOrderProducts,
      recommendProducts,
      newProducts,
      hotProducts
    };

    return successResponse(res, stats, '获取商品统计成功');
  });

  /**
   * 获取商品SKU列表
   */
  getProductSkus = asyncHandler(async (req: Request, res: Response) => {
    const { id } = req.params;

    const product = await Product.findByPk(id);
    if (!product) {
      return errorResponse(res, '商品不存在', 404);
    }

    const skus = await ProductSku.findAll({
      where: { productId: id },
      order: [['createdAt', 'ASC']]
    });

    return successResponse(res, skus, '获取商品SKU列表成功');
  });

  /**
   * 创建商品SKU
   */
  createProductSku = asyncHandler(async (req: Request, res: Response) => {
    const { id } = req.params;
    const skuData = req.body;

    const product = await Product.findByPk(id);
    if (!product) {
      return errorResponse(res, '商品不存在', 404);
    }

    // 检查SKU编码是否重复
    if (skuData.skuCode) {
      const existingSku = await ProductSku.findOne({
        where: { skuCode: skuData.skuCode }
      });
      if (existingSku) {
        return errorResponse(res, 'SKU编码已存在', 400);
      }
    }

    const sku = await ProductSku.create({
      ...skuData,
      productId: id
    });

    return successResponse(res, sku, '创建SKU成功', 200);
  });

  /**
   * 更新商品SKU
   */
  updateProductSku = asyncHandler(async (req: Request, res: Response) => {
    const { id, skuId } = req.params;
    const updateData = req.body;

    const product = await Product.findByPk(id);
    if (!product) {
      return errorResponse(res, '商品不存在', 404);
    }

    const sku = await ProductSku.findOne({
      where: { id: skuId, productId: id }
    });
    if (!sku) {
      return errorResponse(res, 'SKU不存在', 404);
    }

    // 检查SKU编码是否重复
    if (updateData.skuCode && updateData.skuCode !== sku.skuCode) {
      const existingSku = await ProductSku.findOne({
        where: { 
          skuCode: updateData.skuCode,
          id: { [Op.ne]: skuId }
        }
      });
      if (existingSku) {
        return errorResponse(res, 'SKU编码已存在', 400);
      }
    }

    await sku.update(updateData);

    return successResponse(res, sku, '更新SKU成功');
  });

  /**
   * 删除商品SKU
   */
  deleteProductSku = asyncHandler(async (req: Request, res: Response) => {
    const { id, skuId } = req.params;

    const product = await Product.findByPk(id);
    if (!product) {
      return errorResponse(res, '商品不存在', 404);
    }

    const sku = await ProductSku.findOne({
      where: { id: skuId, productId: id }
    });
    if (!sku) {
      return errorResponse(res, 'SKU不存在', 404);
    }

    await sku.destroy();

    return successResponse(res, null, '删除SKU成功');
  });
}

export default new ProductController();